<template>
  <div class="zh-subject-management">
    <div class="zh-table">
      <div class="zh-table-open clear">
        <div class="zh-open-left fl">
          <div class="open-width" style="width: 100px">
            <el-select v-model="listParam.grade_id" filterable placeholder="请选择">
              <el-option v-for="item in orgLevel3" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="open-width" style="width: 100px">
            <el-select v-model="listParam.subject_id" filterable placeholder="请选择">
              <el-option v-for="item in orgSubject" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="open-width" style="width: 100px">
            <el-select v-model="listParam.version_id" filterable placeholder="请选择">
              <el-option v-for="item in orgVersion" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="open-width">
            <el-input v-model="listParam.keyword" placeholder="请输入科目名称搜索" @keyup.enter.native="searchFunc"></el-input>
          </div>
          <el-button type="primary" @click="searchFunc">搜索</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </div>
        <div class="zh-open-right fr">
          <el-button type="primary" @click="saveSubjectBox()">添加科目</el-button>
        </div>
      </div>

      <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
        <div class="zh-table-subject">
          <el-row :gutter="20">
            <template v-for="(item, index) in listData">
              <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6" :key="index">
                <el-card shadow="hover">
                  <div class="card-inner">
                    <div class="subject-content clear">
                      <div class="title-subject fl" :title="item.name">
                        <span>{{ item.name }}</span>
                      </div>
                      <div class="select-subject fr">
                        <i class="el-icon-edit" @click="saveSubjectBox(item)" title="编辑"></i>
                        <i class="el-icon-close" @click="deleteSubject(item)" title="删除"></i>
                      </div>
                    </div>
                    <div class="chapter-subject" :title="changeUoName(item.uo_name)">{{ changeUoName(item.uo_name) }}
                    </div>
                  </div>
                </el-card>
              </el-col>
            </template>
          </el-row>
        </div>

        <div class="table-pagination" v-show="total_number > 20">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="listParam.page_index" :page-sizes="[20, 30, 40, 50, 100]" :page-size="listParam.page_size"
            layout="total, sizes, prev, pager, next, jumper" :total="total_number">
          </el-pagination>
          <div class="pagination-button">
            <el-button @click="getList" type="primary" icon="el-icon-refresh" circle title="刷新数据" size="mini">
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑科目 -->
    <el-dialog :title="title" :visible.sync="addSubject" :before-close="cancelSubject" :close-on-click-modal="false"
      :close-on-press-escape="false" class="addSubject" width="460px">
      <el-form :model="addForm" ref="addForm" :rules="rules" status-icon label-position="left" label-width="80px">
        <el-form-item label="科目名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入科目名称" autocomplete="off" :maxlength="parseInt(10)" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="版本" prop="ver_id">
          <el-select v-model="addForm.ver_id" filterable placeholder="请选择">
            <el-option v-for="item in orgVersion" :key="item.id" v-if="item.id > 0" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用" prop="stu_id">
          <el-checkbox-group v-model="checkboxGrade_id">
            <el-checkbox-button v-for="(item, inx) in orgLevel3" :key="inx" v-if="parseInt(item.id) > 0"
              :label="item.id.toString()">
              {{ item.name }}
            </el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubject">取消</el-button>
        <el-button type="primary" @click="saveSubject">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      app_code: sessionStorage.getItem('CheckSchoolAppCode'),
      loading: {
        status: false,
        txt: '获取数据...',
      },
      checkboxGrade_id: [],//弹框年级选中
      listData: [],//列表数据
      listParam: {//列表数据参数
        grade_id: 0,
        subject_id: 0,
        version_id: 0,
        keyword: '',
        page_index: 1,
        page_size: 20,

      },
      // subjectData:[],//弹框科目下拉
      orgLevelParam: { //获取年级参数
        level: 3,
        direction: 'balance',
      },
      orgLevel3: [{ id: 0, name: '全部年级' }],//年级数据
      orgSubject: [{ id: 0, name: '全部科目' }],//科目数据
      orgVersion: [{ id: 0, name: '全部版本' }],//版本数据
      subjectParam: { //获取科目参数
        type: 2,
        org_id: 1,
        status: 1,
      },
      versionParam: { //获取版本参数
        type: 2,
        org_id: 0,
        sub_id: 0,
        status: 1
      },
      total_number: 0,//数据总shu


      addSubject: false,
      campus: [],
      addForm: {
        id: 0,
        name: '',
        o_ver_id: 0,
        stu_id: [],
        ver_id: '',
      },
      rules: {
        name: [
          { required: true, message: '请填写科目名称', trigger: 'blur' },
          { pattern: this.rules.spaceKey.reg, message: this.rules.spaceKey.msg, trigger: 'blur' },
          { min: 2, max: 10, message: '2~10位字符', trigger: 'blur' }
        ],
        ver_id: [
          { required: true, message: '请选择版本', trigger: 'blur' }
        ],
        stu_id: [
          { required: true, message: '请选择适用学段', trigger: 'blur' }
        ]
      },
      title: '',

    }
  },
  created() {
    this.getOrgLevel3();
    this.getSubject();
    this.getVersion();
    this.getList();
  },
  computed: {
    changeUoName() {
      return (name) => {
        let rename = name ? name.split(',').join('/') : '';
        return rename;
      }
    }
  },
  watch: {
    'listParam.grade_id': {
      handler(newVal, oldVal) {
        this.listParam.subject_id = 0
        this.listParam.version_id = 0

        this.subjectParam.org_id = newVal
        this.getSubject();

        this.versionParam.org_id = newVal;
        this.getVersion();

      }
    },
    'listParam.subject_id': {
      handler(newVal, oldVal) {
        this.listParam.version_id = 0

        this.versionParam.sub_id = newVal;
        this.getVersion();
      }
    }
  },
  methods: {
    cancelSubject() {
      this.$refs.addForm.clearValidate();
      this.addSubject = false;
    },
    searchFunc() {
      this.listParam.page_index = 1;
      this.getList();
    },
    reset() {
      this.orgLevelParam = { //获取年级参数
        level: 3,
        direction: 'balance',
      }
      this.subjectParam = { //获取科目参数
        type: 2,
        org_id: 1,
        status: 1,
      }
      this.versionParam = { //获取版本参数
        type: 2,
        org_id: 0,
        sub_id: 0,
        status: 1
      }
      this.listParam = {
        grade_id: 0,
        subject_id: 0,
        version_id: 0,
        keyword: '',
        page_index: 1,
        page_size: 20,
      }
      this.getList();
    },
    saveSubjectBox(obj = null) {
      this.resetAddform();
      this.addSubject = true
      if (is_empty(obj)) {
        this.title = "添加科目"
      } else {
        this.title = "编辑科目"
        this.getSubjectOne(obj);
      }
    },
    //获取单个版本
    getSubjectOne(obj) {
      let success = (data => {
        this.addForm.o_ver_id = data.data[0].version_id;
        this.addForm.id = data.data[0].subject_id;
        this.addForm.ver_id = data.data[0].version_id;
        this.addForm.name = data.data[0].subject_name;
        this.checkboxGrade_id = data.data[0].grade_id.split(',');
      })
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_subject_data', { params: { subject_id: obj.subject_id, version_id: obj.version_id }, func: { success: success } })
      } else {
        this.$ajax.get('api/cate/subject_data', { params: { subject_id: obj.subject_id, version_id: obj.version_id }, func: { success: success } })
      }
    },
    //保存科目
    saveSubject() {
      this.addForm.stu_id = deep_clone(this.checkboxGrade_id);
      let success = (data => {
        this.addSubject = false;
        this.$message.success(data.msg);
        this.getList();
      })
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (parseInt(this.addForm.id) > 0) {
            if (this.$store.state.checkLevel) {
              this.$ajax.put('api/newlevel/platform_subject', this.addForm, { func: { success: success } })
            } else {
              this.$ajax.put('api/cate/subject', this.addForm, { func: { success: success } })
            }
          } else {
            if (this.$store.state.checkLevel) {
              this.$ajax.post('api/newlevel/platform_subject', this.addForm, { func: { success: success } })
            } else {
              this.$ajax.post('api/cate/subject', this.addForm, { func: { success: success } })
            }
          }
        } else {
          return false;
        }
      })
    },

    //删除科目
    deleteSubject(obj) {
      let yes = (async data => {
        let success = (data => {
          this.$message.success(data.msg);
          if (this.listData.length === 1 && this.listParam.page_index > 1) {
            this.listParam.page_index--;
          }
          this.getList();
        })
        if (this.$store.state.checkLevel) {
          this.$ajax.delete('api/newlevel/platform_subject', { params: { subject_id: obj.subject_id, version_id: obj.version_id }, func: { success: success } })
        } else {
          // 查询是否存在课表数据
          let power = await this.getPowerDelect(obj.subject_id)
          if (!power) {
            this.$ajax.delete('api/cate/subject', { params: { subject_id: obj.subject_id, version_id: obj.version_id }, func: { success: success } })
          } else {
            this.$alert(obj.name + ' 当前存在课表数据，请清空课表才能删除科目。', '提示', {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
          }
        }
      })
      let cancel = (data => { })
      this.e_confirm({ yes: yes, cancel: cancel, txt: '确定删除 ' + obj.name + ' 吗？' });
    },
    async getPowerDelect(id) {
      return new Promise((resolve, reject) => {
        let success = (data => {
          // 接口会返回1 或者[]
          if (data.data === 1) {
            resolve(true)
          }
          resolve(false)
        })
        let date = new Date();
        let dataTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
        this.$ajax.get('api/school/checkSyllabus', { params: { subject_id: id, start_time: dataTime }, func: { success: success } })
      })

    },
    //获取数据
    getList() {
      if (this.$store.state.checkLevel) {
        this.listParam.app_code = this.app_code
      }
      this.loading.status = true;
      let success = (data => {
        console.log(JSON.parse(JSON.stringify(data.data.data)))
        this.loading.status = false;
        this.listData = data.data.data;
        this.total_number = data.data.data_sum;
      })
      let fail = (data => {
        this.loading.status = false;
        this.$message.error(data.msg)
      })
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_subject_data', { params: this.listParam, func: { success: success, fail: fail } })
      } else {
        this.$ajax.get('api/cate/subject_data', { params: this.listParam, func: { success: success, fail: fail } })
      }
    },

    //获取年级
    getOrgLevel3() {
      if (this.$store.state.checkLevel) {
        this.orgLevelParam.app_code = this.app_code
      }
      let success = (data => {
        this.orgLevel3 = data.data;
        this.orgLevel3.unshift({ id: 0, name: '全部年级' })
      })
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_org', { params: this.orgLevelParam, func: { success: success } })
      } else {
        this.$ajax.get('api/org/org', { params: this.orgLevelParam, func: { success: success } })
      }
    },
    //获取科目
    getSubject() {
      if (this.$store.state.checkLevel) {
        this.subjectParam.app_code = this.app_code
      }
      let success = (data => {
        this.orgSubject = data.data;
        this.orgSubject.unshift({ id: 0, name: '全部科目' });
      })
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_subject', { params: this.subjectParam, func: { success: success } })
      } else {
        this.$ajax.get('api/cate/subject', { params: this.subjectParam, func: { success: success } })
      }
    },
    //获取版本
    getVersion() {
      let success = (data => {
        this.orgVersion = data.data;
        this.orgVersion.unshift({ id: 0, name: '全部版本' });
      })
      this.$ajax.get('api/cate/version', { params: this.versionParam, func: { success: success } })
    },
    handleSizeChange(val) {
      this.listParam.page_index = 1;
      this.listParam.page_size = val;
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParam.page_index = val;
      this.getList();
    },
    resetAddform() {
      this.addForm = {
        id: 0,
        name: '',
        ver_id: '',
        stu_id: '',
      };
      this.checkboxGrade_id = [];
    }
  },
}
</script>
<style lang="scss">
.zh-subject-management {
  .zh-table-contents {
    .zh-table-subject {
      .el-col {
        .subject-content {
          .title-subject {
            width: 70%;
            cursor: default;

            &:hover {
              color: #303133;
            }
          }

          .select-subject {
            i:last-child {
              margin-left: 5px;
            }
          }
        }
      }
    }
  }

  .addSubject {
    .el-checkbox-button__inner {
      min-width: 69px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }

    .el-checkbox-button {
      margin-right: 10px;
      margin-bottom: 10px;
    }

    .el-checkbox-button.is-checked .el-checkbox-button__inner {
      border: 1px solid #409EFF;
    }
  }

  .chapter-subject {
    display: -webkit-box;
    min-height: 40px;
    white-space: normal !important;
    text-overflow: ellipsis;
    text-overflow: -o-ellipsis-lastline;
    line-clamp: 2;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}
</style>
